package com.shure.modules.docs.controller;

import fr.opensagres.poi.xwpf.converter.xhtml.Base64EmbedImgManager;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLConverter;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/import")
public class ImportController {

    @PostMapping("/word")
    public ResponseEntity<Map> importWord(@RequestParam("file") MultipartFile file) throws IOException {
        try {
            String htmlContent = convertWordToHtml(file);
            Map<String, Object> response = new HashMap<>();
            response.put("html", htmlContent);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("error", "文件解析失败: " + e.getMessage()));
        }
    }

    private String convertWordToHtml(MultipartFile file) throws Exception {
        try (InputStream is = file.getInputStream()) {
            // 1. 加载Word文档
            XWPFDocument document = new XWPFDocument(is);

            // 2. 创建转换选项
            XHTMLOptions options = XHTMLOptions.create();
            options.setIgnoreStylesIfUnused(false);
            options.setFragment(true);

            // 3. 设置图片处理回调
            options.setImageManager(new Base64EmbedImgManager());

            // 4. 转换HTML
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            XHTMLConverter.getInstance().convert(document, out, options);

            return out.toString("UTF-8");
        }
    }

}
